function X = gauss_sample(mu, C, n)
% From ML homework 2

%GAUSS_SAMPLE Generate independent samples from a Gaussian distribution
%
%   X = GAUSS_SAMPLE(mu, C, n);
%
%       independently generates n Gaussian samples from the Gaussian
%       distribution with mean vector mu and covariance C.
%
%       Suppose the distribution is over a d-dimensional space, then
%       X is a matrix of size d x n, of which each column is a sample.
%

% Created for MIT Course 6.867 (2011 Fall)
%

%% verify input arguments

if ~(isfloat(mu) && ndims(mu) == 2 && size(mu, 2) == 1)
    error('gauss_sample:invalidarg', 'mu should be a numeric column vector.');
end
d = size(mu, 1);

if ~(isfloat(C) && isequal(size(C), [d d]))
    error('gauss_sample:invalidarg', 'C should be a d x d numeric matrix.');
end

if ~(isnumeric(n) && isscalar(n) && n == fix(n) && n >= 0)
    error('gauss_sample:invalidarg', 'n should be an integer scalar.');
end

%% main

Z = randn(d, n);
T = chol(C, 'lower');
X = bsxfun(@plus, T * Z, mu);
